﻿using log4net;
using ServerControl.Model;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web.UI.WebControls;

namespace ServerControl.Dal
{
    public class VideoDal : DbBase
    {
        private static ILog logger = LogManager.GetLogger("VideoDal");

        public static bool Insert(Video video)
        {
            return Instance.Insertable(video).ExecuteCommand() > 0;
        }

        public static bool Delete(string userName, List<int> ids)
        {
            var isSuccess = false;
            var instance = Instance;
            instance.BeginTran();

            try
            {
                isSuccess = instance.Deleteable<Video>().Where(t => t.UserName == userName && ids.Contains(t.Id)).ExecuteCommand() > 0;

                if(isSuccess) 
                {
                    instance.Deleteable<Comment>().Where(t => t.UserName == userName && ids.Contains(t.VideoId)).ExecuteCommand();
                }

                if (isSuccess)
                {
                    instance.CommitTran();
                }
                else
                {
                    instance.RollbackTran();
                }
            }
            catch (Exception ex)
            {
                instance.RollbackTran();
                logger.Error(ex);
            }

            return isSuccess;
        }

        public static bool Update(Video video)
        {
            return Instance.Updateable(video).IgnoreColumns(t => new { t.UserName, t.AddTime }).Where(t=>t.Id == video.Id).ExecuteCommand() > 0;
        }

        public static Video Select(string userName,int id)
        {
            return Instance.Queryable<Video>().Where(t => t.UserName == userName && t.Id == id).First();
        }

        public static List<Video> ListPage(ref int records, int page, int limit, string userName, string remark = "")
        {
            return Instance
                .Queryable<Video>()
                .Where(t => t.UserName == userName)
                .WhereIF(!string.IsNullOrEmpty(remark), s => s.Remark.Contains(remark))
                .ToPageList(page, limit, ref records);
        }
    }
}
